﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

namespace Nirvana
{
    [ExecuteInEditMode]
    public abstract class UIVariableBind : MonoBehaviour
    {
        [Tooltip("The variable table for this bind.")]
        [SerializeField]
        private UIVariableTable uiVariableTable;
        private bool isBind;
        public UIVariableTable VariableTable { get { return uiVariableTable; }}
        protected abstract void BindVariables();
        protected abstract void UnbindVariables();

        void Awake()
        {
            this.Binds();
        }

        void OnDestroy()
        {
            this.UnbindVariables();
            this.isBind = false;
        }

#if UNITY_EDITOR
        void OnValidate()
        {
            PrefabType prefabType = PrefabUtility.GetPrefabType(this.gameObject);
            if (prefabType != PrefabType.Prefab)
            {
                this.UnbindVariables();
                this.isBind = true;
                this.FindVariableTable();
                this.BindVariables();
            }
            else if (this.uiVariableTable == null)
            {
                this.FindVariableTable();
            }
        }
#endif

        public void Binds()
        {
            if (!this.isBind)
            {
                this.isBind = true;
                FindVariableTable();
                this.BindVariables();
            }
        }

        private void FindVariableTable()
        {
            if(this.uiVariableTable == null)
            {
                this.uiVariableTable = this.GetComponentInParentHard<UIVariableTable>();
            }
        }

        public UIVariable FindVariable(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return null;
            }

            if (this.uiVariableTable != null) return this.uiVariableTable.FindVariable(name);
            return null;
        }




    }
}

